<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="下单时间" style="width: 308px">
        <el-date-picker
            v-model="queryParams.placeOrderDateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="订单编号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="商户单号" prop="merchantOrderNo">
        <el-input v-model="queryParams.merchantOrderNo" placeholder="请输入商户订单号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="商户名称" prop="merchantName">
        <el-input v-model="queryParams.merchantName" placeholder="请输入商户名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select filterable clearable v-model="queryParams.orderStatus" size="small" style="width: 190px; margin-right: 10px">
          <el-option v-for="item in orderStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="付款时间" style="width: 308px">
        <el-date-picker
            v-model="queryParams.payDateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="买家姓名" prop="buyUserName">
        <el-input v-model="queryParams.buyUserName" placeholder="请输入买家姓名" clearable @keyup.enter="handleQuery" />
      </el-form-item>

<!--      <el-form-item label="店铺名称" prop="merchantShopName">-->
<!--        <el-input v-model="queryParams.merchantShopName" placeholder="请输入店铺名称" clearable @keyup.enter="handleQuery" />-->
<!--      </el-form-item>-->

      <el-form-item label="商品编码" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入商品编码" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="售后状态" prop="applyAfterSaleState">
        <el-select v-model="queryParams.applyAfterSaleState" size="small" style="width: 190px; margin-right: 10px">
          <el-option v-for="item in sendBackOrderOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>




      <el-form-item label="商品名称" prop="goodsInfo">
        <el-input v-model="queryParams.goodsInfo" placeholder="请输入商品名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="发货时间" style="width: 308px">
        <el-date-picker
            v-model="queryParams.sendDateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="买家电话" prop="buyUserPhone">
        <el-input v-model="queryParams.buyUserPhone" placeholder="请输入买家手机号" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="货物状态" prop="sendStatus">
        <el-select filterable clearable v-model="queryParams.sendStatus" size="small" style="width: 190px; margin-right: 10px">
          <el-option v-for="item in sendStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="开票状态" prop="invoiceState">
        <el-select filterable clearable v-model="queryParams.invoiceState" size="small" style="width: 190px; margin-right: 10px">
          <el-option v-for="item in invoiceStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain :disabled="single" @click="handleConfigOper('cancelPay')">
          取消支付
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain :disabled="single" @click="handleConfigOper('cancelOrder')">
          作废订单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain :disabled="multiple" @click="handleBatchPayment" v-if="!isAdmin">
          批量支付
        </el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button type="success" plain :disabled="single" @click="handleUpdate">-->
<!--          修改-->
<!--        </el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button type="danger" plain  :disabled="multiple" @click="handleDelete" v-hasPermi="['business:balance:remove']">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain @click="exportOrderExcel()" v-if="!isAdmin">批量导入代发</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain @click="exportOrderExcelToShip()" v-if="isAdmin">批量导入代发</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain @click="handleExportDetail">批量导出代发</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain @click="handleExport">订单导出</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="warning" plain @click="batchShipment()" v-if="isAdmin">批量发货</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="warning" :disabled="multiple" plain @click="batchRemark()" v-if="isAdmin">批量发票备注</el-button>
      </el-col>


<!--
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleDetailExport">订单明细导出</el-button>
      </el-col>
-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>



    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderNo" width="200" fixed >
        <template #default="scope">
          <a style="cursor: pointer; color: #20a0ff; margin-right: 10px" @click="openOrderDetail(scope.row.id)" title="点击查看明细">
            {{ scope.row.orderNo}}
          </a>
        </template>
      </el-table-column>
      <el-table-column label="商户编号" align="center" prop="merchantOrderNo" min-width="180" fixed/>
      <el-table-column label="商户名称" align="center" prop="merchantName" min-width="180" fixed/>
<!--      <el-table-column label="店铺名称" align="center" prop="merchantShopName" min-width="200"/>-->
      <el-table-column label="买家姓名" align="center" prop="buyUserName" min-width="150"/>
      <el-table-column label="买家电话" align="center" prop="buyUserPhone" min-width="150"/>
      <el-table-column label="商品编码" align="center" prop="code" min-width="150" class="list-container">
        <template #default="scope">
          <span class="list-item" :title="scope.row.code">{{ scope.row.code }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单总价" align="center" prop="totalPrice" min-width="100"/>
<!--      <el-table-column label="快递单号" align="center" prop="logisticsNumber" min-width="180"/>-->
      <el-table-column label="支付状态" align="center" prop="payStatus" min-width="100">
        <template #default="scope">
          <el-tag type="primary" v-if="scope.row.payStatus === 0">未支付</el-tag>
          <el-tag type="success" v-if="scope.row.payStatus === 1">支付成功</el-tag>
          <el-tag type="error" v-if="scope.row.payStatus === 2">支付失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderStatusStr" min-width="150" >
        <template #default="scope">
          <el-tag type="info" v-if="scope.row.orderStatus === 0">待支付</el-tag>
          <el-tag type="warning" v-if="scope.row.orderStatus === 3">已支付</el-tag>
          <el-tag type="warning" v-if="scope.row.orderStatus === 6">待发货订单</el-tag>
          <el-tag type="warning" v-if="scope.row.orderStatus === 9">已发货订单</el-tag>
          <el-tag type="warning" v-if="scope.row.orderStatus === 12">已收货订单</el-tag>
          <el-tag type="success" v-if="scope.row.orderStatus === 15">已完成订单</el-tag>
          <el-tag type="error"   v-if="scope.row.orderStatus === -3">取消支付订单</el-tag>
          <el-tag type="error"   v-if="scope.row.orderStatus === -4">作废订单</el-tag>
          <el-tag type="warning" v-if="scope.row.orderStatus === -6">申请退款</el-tag>
          <el-tag type="warning" v-if="scope.row.orderStatus === -15">取消退款订单</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="货物状态" align="center" prop="sendStatus" min-width="100">
        <template #default="scope">
          <el-tag type="info" v-if="scope.row.sendStatus === 0">未发货</el-tag>
          <el-tag type="warning" v-if="scope.row.sendStatus === 1">部分发货</el-tag>
          <el-tag type="success" v-if="scope.row.sendStatus === 2">已发货</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发票状态" align="center" prop="invoiceState" min-width="100">
        <template #default="scope">
          <el-tag type="info" v-if="scope.row.invoiceState === 0">未开票</el-tag>
          <el-tag type="success" v-if="scope.row.invoiceState === 1">已开票</el-tag>
        </template>
      </el-table-column>


      <el-table-column label="创建人" align="center" prop="userName" min-width="160" />
      <el-table-column label="付款时间" align="center" prop="payTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.payTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发货时间" align="center" prop="shipTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.shipTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" min-width="190">
        <template #default="scope">
          <el-button link type="primary" @click="openOrderDetail(scope.row.id)">详情</el-button>
          <el-button link type="primary"
              @click="handleOperate(scope.row, scope.row.id, scope.row.orderNo, 'applyRefund')"
              v-if="scope.row.applyAfterSaleState === 0 && !isAdmin
              && (scope.row.orderStatus == 3 ||scope.row.orderStatus == 6 ||scope.row.orderStatus == 9 ||scope.row.orderStatus == 12||scope.row.orderStatus == -15  )">
            申请售后
          </el-button>
          <el-button link type="primary"
            @click="handleOperate(scope.row, scope.row.id, scope.row.orderNo, 'payByCompany')"
            v-if="scope.row.orderStatus === 0 && !isAdmin && scope.row.orderStatus !== -4">支付</el-button>
<!--          <el-button link type="primary" @click="handleConfig(scope.row.id, scope.row.orderNo, 'cancelPay')"-->
<!--            v-if="scope.row.orderStatus === 0">取消支付</el-button>-->
<!--          <el-button link type="primary" @click="handleOperate(scope.row, scope.row.id, scope.row.orderNo, 'shipped')"-->
<!--            v-if="(scope.row.orderStatus === 6 || scope.row.orderStatus === 3) && isAdmin">发货</el-button>-->
          <el-button link type="primary" @click="handleOperate(scope.row, scope.row.id, scope.row.orderNo, 'shipped')"
                     v-if="(scope.row.sendStatus === 0)  && isAdmin && scope.row.applyAfterSaleState === 0 && scope.row.orderStatus !== -4">发货</el-button>
          <el-button link type="primary" @click="handleOperate(scope.row, scope.row.id, scope.row.orderNo, 'shipped')"
                     v-if="(scope.row.sendStatus === 1)  && isAdmin && scope.row.applyAfterSaleState === 0 && scope.row.orderStatus !== -4">补发</el-button>
          <el-button link type="primary" @click="handleConfig(scope.row.id, scope.row.orderNo, 'received')"
            v-if="(scope.row.orderStatus === 9) && !isAdmin">确认收货</el-button>

          <el-button link type="primary" @click="handleRemarkOperate(scope.row, scope.row.id, scope.row.orderNo, scope.row.remark, 'remark')"
            v-if="isAdmin">备注</el-button>


        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
                :pageSizes="[10, 20, 30, 50, 100, 200, 500, 1000]"
    />

    <el-dialog :title="title" v-model="openPayOrder" width="600px" append-to-body>
      <el-form ref="openPayOrderRef" :model="searchParams" label-width="100px">
        <el-form-item label="订单金额：" width="100px">
          <span>{{ searchParams.totalPrice }}</span>
        </el-form-item>
        <el-form-item label="运费金额：" >
          <span>{{ searchParams.freightPrice }}</span>
        </el-form-item>
        <el-form-item label="当前余额：" >
          <span>{{ searchParams.merchantBalance }}</span>
        </el-form-item>
        <span v-if="needRecharge" style="color: red">当前余额不足，请充值！！</span>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="operateOrder" v-if="!needRecharge">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="title" v-model="openShipOrder" width="600px" append-to-body>
      <el-form ref="openShipOrderRef" :model="searchParams" label-width="100px">
        <el-form-item label="物流公司" prop="logisticsCompany">
          <el-input v-model="searchParams.logisticsCompany" placeholder="请输入物流公司" />
        </el-form-item>
        <el-form-item label="物流单号" prop="logisticsNumber">
          <el-input v-model="searchParams.logisticsNumber" placeholder="请输入物流单号" />
        </el-form-item>
        <el-form-item label="运费" prop="freightPrice">
          <el-input v-model="searchParams.freightPrice" type="number" placeholder="请输入运费" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="operateOrder">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="title" v-model="openRefundOrder" width="600px" append-to-body>
      <el-form ref="openRefundOrderRef" :model="searchParams" label-width="100px">
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="searchParams.orderNo" placeholder="请输入订单号" disabled />
        </el-form-item>
        <el-form-item label="退单类型">
          <el-radio-group v-model="searchParams.backType">
            <el-radio label="1">仅退款</el-radio>
            <el-radio label="2">退款退货</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="退款原因">
          <el-select v-model="searchParams.backReasonType" size="small" style="width: 500px; margin-right: 10px">
            <el-option v-for="item in backReasonOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单退款金额" prop="totalPrice">
          <el-input v-model="searchParams.totalPrice" placeholder="请输入订单退款金额" disabled />
        </el-form-item>
        <el-form-item label="运费退款金额" prop="freightPrice">
          <el-input v-model="searchParams.freightPrice" placeholder="请输入运费退款金额" disabled />
        </el-form-item>
        <el-form-item label="退款备注" prop="backRemark">
          <el-input v-model="searchParams.backRemark" type="textarea" placeholder="请输入退款备注" />
        </el-form-item>
        <el-form-item label="图片" prop="img">
          <el-upload class="avatar-uploader" :action="uploadImgServer" accept="jpg,jpeg,png" :headers="{
            token: token
          }" :show-file-list="false" :before-upload="handleBeforeUpload" :on-success="handleUrlSuccess">
            <img style="width: 100px; height: 100px; border: 1px solid #e9e9e9;" v-if="searchParams.img"
              :src="searchParams.img" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="operateOrderBack">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog :title="title" v-model="openRemarkOrder" width="600px" append-to-body>
      <el-form ref="openRemarkRef" :model="searchParams" label-width="100px">

        <el-form-item label="已备注："  v-if="searchParams.oldRemark != null">
          <span>{{ searchParams.oldRemark }}</span>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="searchParams.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="updateOrderInfo">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="title" v-model="openRemarkOrderList" width="600px" append-to-body>
      <el-form ref="openRemarkRef" :model="searchParams" label-width="100px">

        <el-form-item label="批量备注" prop="remark">
          <el-input v-model="searchParams.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="updateRemarkList">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="title" v-model="openbatchShipOrder" width="600px" append-to-body>
      <el-form ref="openbatchShipOrderRef" :model="searchParams" label-width="100px">
        <el-form-item label="物流公司" prop="logisticsCompany">
          <el-input v-model="searchParams.logisticsCompany" placeholder="请输入物流公司" />
        </el-form-item>
        <el-form-item label="物流单号" prop="logisticsNumber">
          <el-input v-model="searchParams.logisticsNumber" placeholder="请输入物流单号" />
        </el-form-item>
        <el-form-item label="运费" prop="freightPrice">
          <el-input v-model="searchParams.freightPrice" type="number" placeholder="请输入运费" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="operatebatchShipOrder">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- Detail 组件 -->
    <Detail ref="detailRef" />
    <!-- 发货单 组件 -->
    <Delivery ref="deliveryRef" @refresh="getList" />
    <!-- 导入订单 组件 -->
    <ExportOrder ref="exportOrderRef"/>

    <ExportOrderToShip ref="exportOrderToShipRef"/>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, delOrder, addOrder, updateOrder, orderOperate, batchShipOrderOperate, updateRemarkOperate,
  batchPayment } from "@/api/business/order";
import { localGet, uploadImgServer, hasEmoji } from "@/api/business/goodsInfo";
import { getMerchant } from "@/api/business/merchant";
import { getIsAdmin } from "@/api/system/user";
import { getIsManage } from "@/api/system/user";
import Detail from './detail.vue';
import Delivery from './delivery.vue';
import ExportOrder from './exportOrder.vue';
import ExportOrderToShip from './exportOrderToShip.vue';
import {useRoute} from 'vue-router';
const { proxy } = getCurrentInstance();
import { ElMessage } from 'element-plus'

const orderList = ref([]);
const open = ref(false);
const openPayOrder = ref(false);
const openShipOrder = ref(false);
const openbatchShipOrder = ref(false);
const openRefundOrder = ref(false);
const openRemarkOrder = ref(false);
const openRemarkOrderList = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const needRecharge = ref(false);
const total = ref(0);
const title = ref("");
const isAdmin = ref(true);//是单条还是多条

const orderStatusOptions = ref([
  {
    value: '',
    label: '全部'
  }, {
    value: 0,
    label: '待支付'
  }, {
    value: 3,
    label: '已支付'
  }, {
    value: 6,
    label: '待发货订单'
  }, {
    value: 9,
    label: '已发货订单'
  }, {
    value: 15,
    label: '已完成订单'
  }, {
    value: -3,
    label: '取消支付订单'
  }, {
    value: -4,
    label: '作废订单'
  }, {
    value: -6,
    label: '申请退款订单'
  }
]);
const payStatusOptions = ref([
  {
    value: '',
    label: '全部'
  }, {
    value: 0,
    label: '未支付'
  }, {
    value: 1,
    label: '支付成功'
  }, {
    value: -1,
    label: '支付失败'
  }
]);
const sendStatusOptions = ref([
  {
    value: '',
    label: '全部'
  },{
    value: 0,
    label: '未发货'
  },{
    value: 1,
    label: '部分发货'
  }, {
    value: 2,
    label: '已发货'
  }
]);
const invoiceStatusOptions = ref([
  {
    value: '',
    label: '全部'
  },{
    value: 0,
    label: '未开票'
  },{
    value: 1,
    label: '已开票'
  }
]);

const sendBackOrderOptions = ref([
  {
    value: 0,
    label: '正常订单'
  },{
    value: 1,
    label: '售后订单'
  },{
    value: 2,
    label: '作废订单'
  }
]);

const backReasonOptions = ref([
  {
    value: 1,
    label: '拍错拍多不喜欢'
  }, {
    value: 2,
    label: '与商家协商一致退款'
  }, {
    value: 3,
    label: '空包裹'
  }, {
    value: 4,
    label: '未按约定时间发货'
  }, {
    value: 5,
    label: '破损'
  }, {
    value: 6,
    label: '物流异常'
  }
]);
const token = localGet('token') || '';
const searchType = ref(false);//跳转之后 和菜单开页面会存在menuCodeRoute的处理问题
const data = reactive({
  uploadImgServer,
  token: localGet('token') || '',
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    merchantOrderNo:null,
    orderStatus: null,
    orderStatusStr: null,
    menuCode: null,
    placeOrderDateRange:null,
    payDateRange:null,
    sendDateRange:null,
    merchantShopName:null,
    code:null,
    buyUserInfo:null,
    goodsInfo:null,
    sendStatus:null,
    logisticsNumber:null,
    buyUserPhone: null,
    buyUserName: null,
    applyAfterSaleState: 0,
    invoiceState:null
  },
  rules: {
  },
  searchParams: {
    id: null,
    orderNo: null,
    menuCode: null,

    price: null,
    creditPaymentAmount: null,
    balanceAmount: null,

    logisticsCompany: null,
    logisticsNumber: null,
    freighPrice: null,

    backType: null,
    backPrice: null,
    freightPrice: null,
    backReasonType: null,
    backReasonName: null,
    backRemark: null,
    img: null,
    merchantBalance:null,
    orderIds : null,
    orderIdsStr : null,
  },
});
const detailRef = ref(null);
const exportOrderRef = ref(null);
const exportOrderToShipRef = ref(null);
const deliveryRef = ref(null);
const detailDialogVisible = ref(false); // 详情对话框是否可见
const route = useRoute();
const menuCodeRoute = route.query.menuCode;
const { queryParams, form, rules, searchParams } = toRefs(data);

/** 查询订单信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.menuCode = menuCodeRoute;

  if(searchType.value == true){
    queryParams.value.menuCode = null;
  }
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  openPayOrder.value = false;
  openShipOrder.value = false;
  openRefundOrder.value = false;
  openbatchShipOrder.value = false;
  openRemarkOrder.value = false;
  openRemarkOrderList.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderNo: null,
    userId: null,
    userName: null,
    merchantId: null,
    merchantName: null,
    merchantShopId: null,
    merchantShopName: null,
    buyUserName: null,
    buyUserPhone: null,
    goodsInfo: null,
    totalPrice: null,
    payStatus: null,
    payType: null,
    payTime: null,
    orderStatus: null,
    orderStatusStr: null,
    shipTime: null,
    delFlag: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    buyerMessage: null,
    creditPaymentAmount: null,
    balanceAmount: null,
    refundReason: null,
    applyAfterSaleState: null,
    refundAmount: null,
    refundState: null
  };
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  searchType.value = true;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除订单？').then(function () {
    return delOrder(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}


/** 删除按钮操作 */
function handleBatchPayment(row) {
  const _ids = row.id || ids.value;

  console.log("----ids----", _ids)

  proxy.$modal.confirm('是否确认批量支付订单？').then(function () {
    // return batchPayment(_ids);
    batchPayment(_ids).then(response => {

      if (response.resultCode === 200) {
        proxy.$modal.msgSuccess("批量支付成功");
        open.value = false;
        getList();
      } else {
        proxy.$modal.msgError(response.message)
      }

    });

  }).then(() => {
    // getList();
    // proxy.$modal.msgSuccess("批量支付成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}
function handleExportDetail() {
  proxy.download('business/order/exportDetail', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

/** 订单明细导出按钮操作 */
function handleDetailExport() {
  proxy.download('business/order/export', {
    ...queryParams.value
  }, `订单列表_${new Date().getTime()}.xlsx`)
}


function handleConfig(id, orderNo, menuCode) {
  searchParams.value.id = id;
  searchParams.value.orderNo = orderNo;
  searchParams.value.menuCode = menuCode;
  proxy.$modal.confirm('是否确认？').then(function () {
    return orderOperate(searchParams.value);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => { });

}

function handleConfigOper(menuCode) {
  const _ids = ids.value[0];
  searchParams.value.orderIds = _ids;
  // searchParams.value.orderNo = orderNo;
  searchParams.value.menuCode = menuCode;
  proxy.$modal.confirm('是否确认？').then(function () {
    return orderOperate(searchParams.value);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => { });

}


/** 弹窗订单操作 */
function handleOperate(row, id, orderNo, menuCode) {

  searchParams.value.id = id;
  searchParams.value.orderNo = orderNo;
  searchParams.value.menuCode = menuCode;
  searchParams.value.totalPrice = row.totalPrice;
  searchParams.value.freightPrice = row.freightPrice;
  if (menuCode === 'payByCompany') {
    //获取商户的信息
    getMerchant(row.merchantId).then(response => {
      console.log("----response.data.balance---", response.data.balance)
      searchParams.value.merchantBalance = response.data.balance;

      //如果订单总额大于剩余余额，需要去充值
      if((searchParams.value.totalPrice + searchParams.value.freightPrice) > searchParams.value.merchantBalance){
        needRecharge.value = true;
      }else{
        needRecharge.value = false;
      }
    });
    openPayOrder.value = true;
  }
  if (menuCode === 'shipped') {
    // openShipOrder.value = true;
    if (deliveryRef.value) deliveryRef.value.init([id]);
  }
  if (menuCode === 'applyRefund') {
    openRefundOrder.value = true;
  }
  if (menuCode === 'remark') {
    searchParams.value.remark = '';
    openRemarkOrder.value = true;
  }
  title.value = "操作";

}
/** 弹窗订单操作 */
function handleRemarkOperate(row, id, orderNo, remark, menuCode) {

  searchParams.value.id = id;
  searchParams.value.orderNo = orderNo;
  searchParams.value.menuCode = menuCode;

  searchParams.value.oldRemark = remark;
  searchParams.value.remark = '';
  openRemarkOrder.value = true;

  title.value = "操作";

}

/** 弹窗订单操作 */
function batchRemark() {
  const _ids = ids.value;
  searchParams.value.orderIds = _ids;

  openRemarkOrderList.value = true;

  title.value = "操作";
}

//批量发货
function batchShipment() {

  // const _ids = ids.value;
  // let orderIdsStr = '';
  // for (let i = 0; i < _ids.length; i++) {
  //   orderIdsStr += _ids[i] + ','
  // }
  // searchParams.value.orderIdsStr = orderIdsStr;
  // searchParams.value.menuCode = "batchShipment";
  // openbatchShipOrder.value = true;
  // title.value = "操作";

  if (ids.value.length > 0) {
    if (deliveryRef.value) deliveryRef.value.init(ids.value);
  }
}

//批量发货
function exportOrderExcel() {
  if (exportOrderRef.value) exportOrderRef.value.init(ids.value);
}

function exportOrderExcelToShip() {
  if (exportOrderToShipRef.value) exportOrderToShipRef.value.init(ids.value);
}

/** 弹窗后操作 */
function operateOrder() {

  proxy.$modal.confirm('是否确认？').then(function () {
    return orderOperate(searchParams.value);
  }).then(() => {
    getList();

    openPayOrder.value = false;
    openShipOrder.value = false;
    openRefundOrder.value = false;
    openRemarkOrder.value = false;

    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => { });

}

/** 弹窗后操作 */
function operateOrderBack() {

  let backType = searchParams.value.backType;
  if(backType === null || backType ===  undefined){
    ElMessage.error('请选择-退单类型')
    return false
  }

  let backReasonType = searchParams.value.backReasonType;
  if(backReasonType === null || backReasonType ===  undefined){
    ElMessage.error('请选择-退款原因')
    return false
  }

  proxy.$modal.confirm('是否确认？').then(function () {
    return orderOperate(searchParams.value);
  }).then(() => {
    getList();

    openPayOrder.value = false;
    openShipOrder.value = false;
    openRefundOrder.value = false;
    openRemarkOrder.value = false;

    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => { });

}

/** 弹窗后操作 */
function updateOrderInfo() {

  let remark = searchParams.value.remark;
  if(remark === null || remark ===  undefined){
    ElMessage.error('请输入备注')
    return false
  }

  proxy.$modal.confirm('是否确认？').then(function () {
    return updateOrder(searchParams.value);
  }).then(() => {
    getList();

    openPayOrder.value = false;
    openShipOrder.value = false;
    openRefundOrder.value = false;
    openRemarkOrder.value = false;

    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => { });

}

/** 弹窗后操作 */
function updateRemarkList() {

  let remark = searchParams.value.remark;
  if(remark === null || remark ===  undefined){
    ElMessage.error('请输入备注')
    return false
  }

  console.log("----searchParams.value-----", searchParams.value)

  proxy.$modal.confirm('是否确认？').then(function () {
    return updateRemarkOperate(searchParams.value);
  }).then(() => {
    getList();

    openRemarkOrderList.value = false;

    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => { });

}




/** 弹窗后操作 */
function operatebatchShipOrder() {

  proxy.$modal.confirm('是否确认？').then(function () {
    return batchShipOrderOperate(searchParams.value);
  }).then(() => {
    getList();

    openPayOrder.value = false;
    openShipOrder.value = false;
    openRefundOrder.value = false;
    openbatchShipOrder.value = false;
    openRemarkOrder.value = false;

    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => { });

}


function handleBeforeUpload(file) {
  const sufix = file.name.split('.')[1] || ''
  if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
    ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
    return false
  }
}
function handleUrlSuccess(val) {
  searchParams.value.img = val.url || ''
}

// 详情
function openOrderDetail(id) {
  if (detailRef.value) detailRef.value.init(id);
}


function init() {
  // getIsAdmin().then(response => {
  getIsManage().then(response => {
    console.log("----isAdmin.value-----" , response)
    //为false时，代表是子商户
    isAdmin.value = response;
  });
}

init();
getList();
</script>

<style scoped>
.add {
  display: flex;
}

.add-container {
  flex: 1;
  height: 100%;
}

.avatar-uploader {
  width: 100px;
  height: 100px;
  color: #ddd;
  font-size: 30px;
}

.avatar-uploader-icon {
  display: block;
  width: 100%;
  height: 100%;
  border: 1px solid #e9e9e9;
  padding: 32px 17px;
}
</style>

<style>
.list-container {
  width: 200px; /* 设定一个宽度 */
}

.list-item {
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏溢出的内容 */
  text-overflow: ellipsis; /* 显示省略号 */
}
</style>